//
//  PhotoPickerViewController.swift
//  WBDemo
//
//  Created by Meng on 17/3/10.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class PhotoPickerViewController: UICollectionViewController, PhotoPickerCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
    var images = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        //self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    // MARK: UICollectionViewDataSource

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return images.count + 1
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoPickerCell
        cell.delegate = self
        // Configure the cell
        cell.image = (indexPath.item >= images.count) ? nil : images[indexPath.item]
        return cell
    }
    
    // MARK: - PhotoPickerCellDelegate
    func photoPickerCellDidAddButtonClick(cell: PhotoPickerCell) {
        guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else {
            return
        }
        let pic = UIImagePickerController()
        pic.sourceType = .photoLibrary
        pic.delegate = self
        present(pic, animated: true, completion: nil)
    }
    func photoPickerCellDidRemoveButtonClick(cell: PhotoPickerCell) {
        let indexPath = collectionView!.indexPath(for: cell)!
        images.remove(at: indexPath.item)
        collectionView?.reloadData()
    }
    
    // MARK: - UIImagePickerControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        picker.dismiss(animated: true, completion: nil)
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let newImage = drawImage(image: image, width: UIScreen.main.bounds.width)
        images.append(newImage)
        collectionView?.reloadData()
    }
    
    // 压缩图片
    func drawImage(image: UIImage, width: CGFloat) -> UIImage {
        let height = (width * image.size.height) / image.size.width
        let size = CGSize(width: width, height: height)
        // 开启上下文
        UIGraphicsBeginImageContext(size)
        // 将图片画到上下文中
        image.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
        // 获取新的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        // 关闭上下文
        UIGraphicsEndImageContext()
        return newImage
    }

}

protocol PhotoPickerCellDelegate: NSObjectProtocol {
    func photoPickerCellDidAddButtonClick(cell: PhotoPickerCell)
    func photoPickerCellDidRemoveButtonClick(cell: PhotoPickerCell)
}

class PhotoPickerCell: UICollectionViewCell {
    
    weak var delegate: PhotoPickerCellDelegate?
    
    @IBOutlet weak var button: UIButton!
    
    @IBOutlet weak var removeButton: UIButton!
    
    var image: UIImage? {
        didSet {
            if image == nil {
                removeButton.isHidden = true
                button.isUserInteractionEnabled = true
                button.setBackgroundImage(UIImage(named: "compose_pic_add"), for: .normal)
                button.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), for: .highlighted)
            } else {
                removeButton.isHidden = false
                button.isUserInteractionEnabled = false
                button.setBackgroundImage(image, for: .normal)
            }
        }
    }
    
    @IBAction func addPhotoButtonClick(_ sender: Any) {
        guard let tempDelegate = delegate else {
            return
        }
        tempDelegate.photoPickerCellDidAddButtonClick(cell: self)
    }
    @IBAction func removeButtonClick() {
        guard let tempDelegate = delegate else {
            return
        }
        tempDelegate.photoPickerCellDidRemoveButtonClick(cell: self)
    }
}

class PhotoPickerFlowLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        let margin: CGFloat = 10
        let col: CGFloat = 3
        let itemWH = (collectionView!.bounds.width - margin * (col + 1)) / col
        itemSize = CGSize(width: itemWH, height: itemWH)
        minimumLineSpacing = margin
        minimumInteritemSpacing = margin
        sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
    }
}
